package com.stefan.framework;

import com.stefan.framework.protocol.Protocol;
import com.stefan.framework.protocol.ProtocolFactory;
import com.stefan.framework.protocol.URL;
import com.stefan.framework.protocol.http.HttpClient;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;

public class ProxyFactory<T> {
    /**
     * 创建代理对象
     * @param interfaceClass 接口类
     * @param <T> 泛型类型
     * @return 代理对象
     */
    public static <T> T createProxy(Class<T> interfaceClass) {
        return (T) Proxy.newProxyInstance(
                interfaceClass.getClassLoader(),
                new Class<?>[]{interfaceClass},
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        Invocation invocation = new Invocation(interfaceClass.getName(),
                                method.getName(), method.getParameterTypes(), args);
//                        String result = httpClient.send("localhost", 8080, invocation);
                        List<URL> urls = RemoteAddressRegister.get(interfaceClass.getName());
                        URL random = LoadBalancer.random(urls);

//                        HttpClient httpClient = new HttpClient();
//                        String result = httpClient.send(random.getHostname(), random.getPort(), invocation);
                        Protocol protocol = ProtocolFactory.getProtocol();
                        String result = protocol.send(random,invocation);
                        return result;
                    }
                }
        );


    }
}
